<?php

namespace plugin\ycMassage\app\admin\controller;

use plugin\ycMassage\app\BaseController;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserDealer;
use plugin\ycMassage\app\model\MassageUserDealerBill;
use plugin\ycMassage\app\model\MassageUserDealerLog;
use plugin\ycMassage\app\model\MassageUserDealerStatistics;
use plugin\ycMassage\app\model\MassageUserWallet;
use plugin\ycMassage\app\model\MassageWithdrawal;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\MoneyAction;
use support\Request;
use think\facade\Cache;
use think\facade\Db;

class DealerController extends BaseController
{
    public function index(Request $request)
    {
        $echarts = Cache::get('Massage.statistic.admin.dealer.' . $request->saas_appid);
        $echarts = json_decode($echarts);
        if (!$echarts) {
            $series = [
                'name' => '',
                'type' => 'line',
                'stack' => 'Total',
                'smooth' => true,
                'data' => [],
            ];
            $echarts = [
                'legend' => [
                    'data' => ['订单量', '订单额', '分销额', '分销量', '提现额(存量)', '提现额', '代理数', '用户增长']
                ],
                'xAxis' => [
                    'data' => []
                ],
                'series' => []
            ];
            $OrderNum = [];
            $OrderPrice = [];
            $DealerLogNum = [];
            $DealerPrice = [];
            $WithdrawalPriceStock = [];
            $WithdrawalPrice = [];
            $DealerPeopleNum = [];
            $UserNum = [];
            for ($i = 7; $i > 0; $i--) {
                $time = strtotime("-{$i} day");
                $whereDay = date('Y-m-d', $time);
                $date = date('m-d', $time);
                $echarts['xAxis']['data'][] = $date;
                $MassageUserDealerStatistics = MassageUserDealerStatistics::where(['saas_appid' => $request->saas_appid])->whereDay('create_time', $whereDay)->find();
                if ($MassageUserDealerStatistics) {
                    $OrderNum[] = $MassageUserDealerStatistics->OrderNum;
                    $OrderPrice[] = $MassageUserDealerStatistics->OrderPrice;
                    $DealerLogNum[] = $MassageUserDealerStatistics->DealerLogNum;
                    $DealerPrice[] = $MassageUserDealerStatistics->DealerPrice;
                    $WithdrawalPriceStock[] = $MassageUserDealerStatistics->WithdrawalPriceStock;
                    $WithdrawalPrice[] = $MassageUserDealerStatistics->WithdrawalPrice;
                    $DealerPeopleNum[] = $MassageUserDealerStatistics->DealerPeopleNum;
                    $UserNum[] = $MassageUserDealerStatistics->UserNum;
                } else {
                    $OrderNum[] = 0;
                    $OrderPrice[] = 0;
                    $DealerLogNum[] = 0;
                    $DealerPrice[] = 0;
                    $WithdrawalPriceStock[] = 0;
                    $WithdrawalPrice[] = 0;
                    $DealerPeopleNum[] = 0;
                    $UserNum[] = 0;
                }
            }
            $series['name'] = '订单量';
            $series['data'] = $OrderNum;
            $echarts['series'][] = $series;
            $series['name'] = '订单额';
            $series['data'] = $OrderPrice;
            $echarts['series'][] = $series;
            $series['name'] = '分销额';
            $series['data'] = $DealerLogNum;
            $echarts['series'][] = $series;
            $series['name'] = '分销量';
            $series['data'] = $DealerPrice;
            $echarts['series'][] = $series;
            $series['name'] = '提现额(存量)';
            $series['data'] = $WithdrawalPriceStock;
            $echarts['series'][] = $series;
            $series['name'] = '提现额';
            $series['data'] = $WithdrawalPrice;
            $echarts['series'][] = $series;
            $series['name'] = '代理数';
            $series['data'] = $DealerPeopleNum;
            $echarts['series'][] = $series;
            $series['name'] = '用户增长';
            $series['data'] = $UserNum;
            $echarts['series'][] = $series;
            $ex = strtotime('23:59:59') - time();
            Cache::set('Massage.statistic.admin.dealer.' . $request->saas_appid, json_encode($echarts, JSON_UNESCAPED_UNICODE), $ex);
        }
        $data = [
            'echarts'          =>  $echarts,
            'user' => [
                'OrderNum' => MassageUserDealer::where(['saas_appid' => $request->saas_appid])->sum('order_num'),
                'OrderPrice' => MassageUserDealer::where(['saas_appid' => $request->saas_appid])->sum('order_price'),
                'DealerLogNum' => MassageUserDealerLog::where(['saas_appid' => $request->saas_appid])->count('id'),
                'DealerPrice' => MassageUserWallet::where(['saas_appid' => $request->saas_appid])->sum('dealer_money_sum'),
                'WithdrawalPriceStock' => MassageUserWallet::where(['saas_appid' => $request->saas_appid])->sum('dealer_money'),
                'WithdrawalPrice' => MassageWithdrawal::where(['saas_appid' => $request->saas_appid,'action'=>ActionIdentity::DEALER['value']])->sum('money'),
                'DealerPeopleNum' => MassageUserDealer::where(['saas_appid' => $request->saas_appid])->count('uid'),
                'UserNum' => MassageUser::where(['saas_appid' => $request->saas_appid])->whereNotNull('dealer_uid')->count('id'),
            ],
            'config' => getHpConfig('', $request->saas_appid, 'dealer')
        ];
        return parent::successRes($data);
    }
    public function applyGetTable(Request $request)
    {
        $builder = new ListBuilder;
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID'
        ]);
        $data    = $builder
            ->addActionOptions('操作', [
                'width' => 180
            ])
            ->pageConfig()
            ->addRightButton('applyHandleResolve', '通过', [
                'type'   => 'confirm',
                'api' => $this->pluginPrefix . '/admin/Dealer/applyHandleResolve',
                'aliasParams' => [
                    'uid' => 'uid'
                ],
            ], [
                'title'   => '温馨提示',
                'content' => '是否确认通过',
            ], [
                'type' => 'primary',
                'link' => true
            ])
            ->addRightButton('applyHandleReject', '驳回', [
                'type'   => 'confirm',
                'api'    => $this->pluginPrefix . '/admin/Dealer/applyHandleReject',
                'aliasParams' => [
                    'uid' => 'uid'
                ],
            ], [
                'title'   => '温馨提示',
                'content' => '是否确认驳回，并删除该数据',
            ], [
                'type' => 'error',
                'link' => true
            ])
            ->addColumn('uid', 'UID', [
                'width' => 100
            ])
            ->addColumnEle('user.headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('user.nickname', '用户昵称')
            ->addColumn('create_time', '创建时间', [
                'width' => 200
            ])
            ->addColumn('apply_price', '申请价格', [
                'width' => 100
            ])
            ->addColumnEle('state', '审核', [
                'width'  => 90,
                'params' => [
                    'type'    => 'tags',
                    'options' => [
                        0 => '待审核',
                        1 => '通过',
                    ],
                    'style'   => [
                        0 => [
                            'type' => 'tertiary'
                        ],
                        1 => [
                            'type' => 'success'
                        ],
                    ],
                ],
            ])
            ->create();
        return parent::successRes($data);
    }
    public function apply(Request $request)
    {
        $limit = $request->get('limit', 20);
        $where = [];
        $where[] = ['state', '=', 0];
        $uid = $request->get('uid', '');
        if ($uid) {
            $where[] = ['uid', '=', $uid];
        }
        $where[] = ['saas_appid', '=', $request->saas_appid];
        $Data  = MassageUserDealer::where($where)->with(['user'])->order('create_time desc')->paginate($limit)->each(function ($item) {
        })
            ->toArray();
        return parent::successRes($Data);
    }
    public function applyHandleResolve(Request $request)
    {
        $uid = $request->get('uid');
        $model = MassageUserDealer::where(['uid' => $uid, 'saas_appid' => $request->saas_appid])->find();
        if (!$model) {
            return parent::fail('数据不存在');
        }
        $model->state = 1;
        if (!$model->save()) {
            return parent::fail('操作失败');
        }
        return parent::success('操作成功');
    }
    public function applyHandleReject(Request $request)
    {
        $uid = $request->get('uid');
        $model = MassageUserDealer::where(['uid' => $uid, 'saas_appid' => $request->saas_appid])->find();
        if (!$model) {
            return parent::fail('数据不存在');
        }
        Db::startTrans();
        try {
            /* 退款业务 */
            MassageOrders::refund($model->orders_id, null, [
                'money' => $model->apply_price
            ]);
            /* 退款业务 */
            $model->delete();
            Db::commit();
            return parent::success('操作成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return parent::fail($th->getMessage());
        }
    }
    public function personnelGetTable(Request $request)
    {
        $builder = new ListBuilder;
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID'
        ]);
        $data    = $builder
            ->addActionOptions('操作', [
                'width' => 180
            ])
            ->pageConfig()
            ->addRightButton('personnelDelete', '冻结', [
                'type'   => 'confirm',
                'api'    => $this->pluginPrefix . '/admin/Dealer/personnelDelete',
                'aliasParams' => [
                    'uid' => 'uid'
                ],
                'params' => [
                    'field' => 'state',
                    'value' => 1
                ]
            ], [
                'title'   => '温馨提示',
                'content' => '是否确认冻结',
            ], [
                'type' => 'error',
                'link' => true
            ])
            ->addRightButton('personnelDelete', '解冻', [
                'type'   => 'confirm',
                'api'    => $this->pluginPrefix . '/admin/Dealer/personnelDelete',
                'aliasParams' => [
                    'uid' => 'uid'
                ],
                'params' => [
                    'field' => 'state',
                    'value' => 2
                ]
            ], [
                'title'   => '温馨提示',
                'content' => '是否确认冻结',
            ], [
                'type' => 'primary',
                'link' => true
            ])
            ->addColumn('uid', 'UID', [
                'width' => 100
            ])
            ->addColumnEle('user.headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('user.nickname', '用户昵称')
            ->addColumn('create_time', '创建时间', [
                'width' => 200
            ])
            ->addColumn('people_num', '邀请人数')
            ->addColumn('wallet.dealer_money', '可提现余额')
            ->addColumn('order_num', '订单数')
            ->addColumn('order_price', '订单总金额')
            ->addColumn('wallet.dealer_money_sum', '分销总奖励')
            ->addColumn('apply_price', '申请价格')
            ->create();
        return parent::successRes($data);
    }
    public function personnel(Request $request)
    {
        $limit = $request->get('limit', 20);
        $where = [];
        $where[] = ['state', 'in', [1, 2]];
        $uid = $request->get('uid', '');
        if ($uid) {
            $where[] = ['uid', '=', $uid];
        }
        $where[] = ['saas_appid', '=', $request->saas_appid];
        $Data  = MassageUserDealer::where($where)->with(['user','wallet'])->order('create_time desc')->paginate($limit)->each(function ($item) {
        })
            ->toArray();
        return parent::successRes($Data);
    }
    public function personnelDelete(Request $request)
    {
        $uid = $request->get('uid');
        $model = MassageUserDealer::where(['uid' => $uid, 'saas_appid' => $request->saas_appid])->find();
        if (!$model) {
            return parent::fail('数据不存在');
        }
        Db::startTrans();
        try {
            $model->state = $model->state === 1 ? 2 : 1;
            $model->save();
            Db::commit();
            return parent::success('操作成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return parent::fail('操作失败');
        }
    }
    public function logGetTable(Request $request)
    {
        $builder = new ListBuilder;
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID'
        ]);
        $data    = $builder
            ->pageConfig()
            ->addColumn('id', '序号', [
                'width' => 100
            ])
            ->addColumn('from_uid', 'UID', [
                'width' => 100
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '贡献者')
            ->addColumn('uid', 'UID', [
                'width' => 100
            ])
            ->addColumnEle('user.headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('user.nickname', '受益者')
            ->addColumn('create_time', '创建时间', [
                'width' => 200
            ])
            ->addColumn('level_text', '关系')
            ->addColumn('price', '奖励')
            ->addColumn('order_price', '订单分销总金额')
            ->addColumn('order_proportion', '订单分销比例(%)')
            ->addColumn('proportion_level', '分销比例(%)')
            ->create();
        return parent::successRes($data);
    }
    public function log(Request $request)
    {
        $limit = $request->get('limit', 20);
        $where = [];
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['uid', '=', $uid];
        }
        $where[] = ['saas_appid', '=', $request->saas_appid];
        $Data  = MassageUserDealerLog::where($where)->with(['user',  'fromUser'])->order('id desc')
            ->paginate($limit)
            ->each(function ($item) {
                switch ($item->level) {
                    case 1:
                        $item->level_text = '直推';
                        break;
                    case 2:
                        $item->level_text = '间推';
                        break;
                    case 3:
                        $item->level_text = '三级';
                        break;
                }
            })
            ->toArray();
        return parent::successRes($Data);
    }
    public function billGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID搜索'
        ]);
        $builder->addScreen('mobile', 'input', '手机号', [
            'placeholder' => '手机号搜索'
        ]);
        $builder->addColumn('id', 'ID', [
            'width' => 90
        ]);
        $builder->addColumn('uid', 'UID', [
            'width' => 90
        ])
            ->addColumn('mobile', '手机号', [
                'width' => 120
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120
            ])
            ->addColumn('money', '变动金额', [
                'width' => 120
            ])
            ->addColumn('old_money', '变动前', [
                'width' => 120
            ])
            ->addColumn('new_money', '变动后', [
                'width' => 120
            ])
            ->addColumnEle('action', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => MoneyAction::dictOptions(),
                    'style' => MoneyAction::dictOptions('style'),
                ],
            ])
            ->addColumn('remarks', '备注')
            ->addColumn('create_time', '时间', [
                'width' => 160
            ]);
        return $this->successRes($builder->create());
    }
    public function bill(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [];
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['log.uid', '=', $uid];
        }
        $where[] = ['log.saas_appid', '=', $request->saas_appid];
        $data = MassageUserDealerBill::where($where)
            ->alias('log')
            ->join('massage_user u', 'log.uid=u.id', 'LEFT')
            ->order('log.id desc')
            ->field('log.*,u.mobile,u.nickname,u.headimg')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->nickname = base64_decode($item->nickname);
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
            });
        return $this->successRes($data);
    }
}
